import React, { useState, useEffect } from "react";
import { Layout, theme, Tag, Breadcrumb } from "antd";
import { Outlet, useNavigate, useLocation } from "react-router-dom";
import MenuCom from "../components/Menu";
import HeaderComponent from "../components/Header";
import menuItems from '../assets/Json/MenuJson/menu';

const { Header, Content, Sider } = Layout;

const MainLay = () => {
  const [username, setUsername] = useState(sessionStorage.getItem("users") || "");
  const [tags, setTags] = useState([]);
  const [breadcrumbItems, setBreadcrumbItems] = useState([]);
  const [currentMenuKey, setCurrentMenuKey] = useState(sessionStorage.getItem("pathKey") || "1");
  const [openKeys, setOpenKeys] = useState([]);

  const {
    token: { colorBgContainer, borderRadiusLG },
  } = theme.useToken();

  const navtor = useNavigate();
  const location = useLocation();

  useEffect(() => {
    const storedTags = JSON.parse(sessionStorage.getItem("tags"));
    if (storedTags) {
      setTags(storedTags);
    }
  }, []);

  useEffect(() => {
    sessionStorage.setItem("tags", JSON.stringify(tags));
  }, [tags]);

  useEffect(() => {
    const currentKey = sessionStorage.getItem("pathKey");
    const newBreadcrumbItems = getBreadcrumbItems(currentKey, menuItems);
    setBreadcrumbItems(newBreadcrumbItems.length > 0 ? newBreadcrumbItems : [{ label: "首页" }]);
  }, [location.pathname]);

  useEffect(() => {
    const storedOpenKeys = JSON.parse(sessionStorage.getItem("openKeys") || "[]");
    setOpenKeys(storedOpenKeys);
  }, []);

  const handleTagClose = (key) => {
    const indexToRemove = tags.findIndex(tag => tag.key === key);
    const updatedTags = tags.filter(tag => tag.key !== key);
    setTags(updatedTags);

    if (updatedTags.length === 0) {
      navtor("/");
      sessionStorage.removeItem("pathKey");
      setBreadcrumbItems([{ label: "首页" }]);
      return;
    }

    let newKey;
    if (location.pathname === tags[indexToRemove].url) {
      if (indexToRemove === 0) {
        const nextTag = updatedTags[0];
        newKey = nextTag.key;
        navtor(nextTag.url);
      } else {
        const previousTag = updatedTags[indexToRemove - 1];
        newKey = previousTag.key;
        navtor(previousTag.url);
      }
    } else {
      newKey = sessionStorage.getItem("pathKey");
    }

    sessionStorage.setItem("pathKey", newKey);
    setCurrentMenuKey(newKey); // 更新侧边栏选中项
    const newBreadcrumbItems = getBreadcrumbItems(newKey, menuItems);
    setBreadcrumbItems(newBreadcrumbItems.length > 0 ? newBreadcrumbItems : [{ label: "首页" }]);
  };

  const handleTagClick = (url, key) => {
    sessionStorage.setItem("pathKey", key);
    setCurrentMenuKey(key); // 更新侧边栏选中项
    setOpenKeys(getOpenKeys(key, menuItems)); // 展开父级菜单
    const newBreadcrumbItems = getBreadcrumbItems(key, menuItems);
    setBreadcrumbItems(newBreadcrumbItems.length > 0 ? newBreadcrumbItems : [{ label: "首页" }]);
    navtor(url);
  };

  const getBreadcrumbItems = (pathKey, items) => {
    for (let item of items) {
      if (item.key === pathKey) {
        return [{ label: item.label }];
      }
      if (item.children) {
        const childBreadcrumb = getBreadcrumbItems(pathKey, item.children);
        if (childBreadcrumb.length > 0) {
          return [{ label: item.label }, ...childBreadcrumb];
        }
      }
    }
    return [];
  };

  const getOpenKeys = (pathKey, items, currentOpenKeys = []) => {
    for (let item of items) {
      if (item.key === pathKey) {
        return currentOpenKeys;
      }
      if (item.children) {
        const openKeys = getOpenKeys(pathKey, item.children, [...currentOpenKeys, item.key]);
        if (openKeys.length > 0) {
          return openKeys;
        }
      }
    }
    return [];
  };

  useEffect(() => {
    sessionStorage.setItem('openKeys', JSON.stringify(openKeys));
  }, [openKeys]);

  return (
    <Layout style={{ height: "100vh" }}>
      <Sider
        breakpoint="lg"
        collapsedWidth="0"
        style={{
          background: "#015478",
          boxShadow: "5px 5px 10px rgba(0,0,0,0.5)",
        }}
      >
        <div
          style={{
            width: "100%",
            display: "flex",
            alignItems: "center",
            flexDirection: "column",
            justifyContent: "start",
            padding: "20px 0",
            fontWeight: "bold",
            fontSize: "17px",
            color: "white",
          }}
        >
          <p>百奥华兴项目管理系统</p>
        </div>
        <MenuCom 
          tags={tags} 
          setTags={setTags} 
          current={currentMenuKey} 
          setCurrent={setCurrentMenuKey}
          openKeys={openKeys}
          setOpenKeys={setOpenKeys}
        />
      </Sider>
      <Layout>
        <HeaderComponent />
        <Content style={{ overflow: "auto" }}>
          <div
            style={{
              padding: 10,
              height: "100%",
              background: "#F2F2F2",
              borderRadius: borderRadiusLG,
              boxSizing: "border-box",
            }}
          >
            <Breadcrumb style={{ marginBottom: "10px" }}>
              {breadcrumbItems.map((item, index) => (
                <Breadcrumb.Item key={index}>
                  {item.label}
                </Breadcrumb.Item>
              ))}
            </Breadcrumb>

            <div style={{ marginBottom: "10px" }}>
              {tags.map(tag => (
                <Tag
                  key={tag.key}
                  closable={tags.length > 1}
                  onClose={() => handleTagClose(tag.key)}
                  onClick={() => handleTagClick(tag.url, tag.key)}
                  style={{ cursor: "pointer" }}
                >
                  {tag.label}
                </Tag>
              ))}
            </div>

            <Outlet />
          </div>
        </Content>
      </Layout>
    </Layout>
  );
};

export default MainLay;
